package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.repository.ApArticleSearchRepository;
import com.heima.search.repository.ApAssociateWordsRepository;
import com.heima.search.service.IApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 联想词的服务实现类
 */
@Service
public class ApAssociateWordsServiceImpl implements IApAssociateWordsService {

    @Autowired
    MongoTemplate mongoTemplate; // mongo数据库

    @Autowired
    ApAssociateWordsRepository associateWordsRepository; // es 的 联想词的仓库接口

    /**
     * 查询关联词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        //1.判断用户输入的关键字为空, 不需要查询            trim 去掉前后空格
        if (dto == null
                || StringUtils.isEmpty(dto.getSearchWords())
                || StringUtils.isEmpty(dto.getSearchWords().trim())){
            // 为空的话, 直接返回, 不需要查询联想词
            return ResponseResult.okResult();
        }

        // Query query = new Query();
        // query.addCriteria(Criteria.where("associateWords").regex("^" + dto.getSearchWords() + ".*$"));
        // query.with(PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createdTime"));
        // List<ApAssociateWords> words = mongoTemplate.find(query, ApAssociateWords.class);

        //2.根据用户传入的关键字在联想词表中进行查询 用户输入关键词前面部分, 补全后面部分
        //2.1 分页条件
        PageRequest page = PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createTime");
        //3. 进行联想词查询, 调用联想词仓库接口里的方法完成查询
        List<ApAssociateWords> words =
                associateWordsRepository.findTopByAssociateWordsStartingWith(dto.getSearchWords(), page);
        //4. 返回给前端页面
        return ResponseResult.okResult(words);
    }
}
